package de.stalinski.accounting.mail;

import de.stalinski.accounting.ConsumersConnector;
import de.stalinski.accounting.PricesTableConnector;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;

public class SmtpSimple implements Runnable {

    private Thread t = null;
    private long timeStamp = System.currentTimeMillis();
    private long sendAt;
    private static final String SMTP_HOST_NAME = "smtp.web.de";
    //Enter username here
    private static final String SMTP_AUTH_USER = "" ;
    //Enter password here
    private static final String SMTP_AUTH_PWD = "";
    private static final String FROM_MAIL = "Mario_Stalinski@web.de";
    private static final String FROM_NAME = "Kassenwart S! Frankonia-Brunonia";
    private static final String SUBJECT = "Bierrechnung";
    private static final long HOURS = 24;
    private static final long MINUTES = 60 * HOURS;
    private static final long INTERVAL = MINUTES * 60 * 1000;

    public SmtpSimple() {
        if (t == null) {
            System.out.println("Creating new Thread");
            timeStamp = System.currentTimeMillis();
            sendAt = timeStamp + INTERVAL;
            t = new Thread(this);
            t.start();
        }
    }

    public void destroyMailer() {
        System.out.println("Destroying!");
        if (t != null && !t.isInterrupted()) {
            System.out.println("Stopping Thread, exit!");
            t.interrupt();
            t = null;
        }
    }

    public void initSend() throws SQLException, AddressException, ClassNotFoundException, Exception {
        try {

            HashMap<String, Double> recipients = new ConsumersConnector().getRecipients();
            ArrayList<String> mailAddresses = new ConsumersConnector().getMailAddresses();

            for (String s : mailAddresses) {
                Double sum = recipients.get(s);
                String exFn = "";
                String exSn = "";
                String exMail = "";
                int firstDelim = 0;
                int secondDelim = 0;
                for (int i = 0; i < s.length(); i++) {
                    exFn += s.charAt(i);
                    if (s.charAt(i) == '|') {
                        firstDelim = i;
                        exFn = exFn.substring(0, exFn.length() - 1);
                        break;
                    }
                }
                for (int i = firstDelim + 1; i < s.length(); i++) {
                    exSn += s.charAt(i);
                    if (s.charAt(i) == '|') {
                        secondDelim = i;
                        exSn = exSn.substring(0, exSn.length() - 1);
                        break;
                    }
                }
                exMail = s.substring(secondDelim + 1);
                if (sum != null) {
                    if (sum > 15.0) {
                        InternetAddress mailTo = new InternetAddress(exMail);
                        System.out.println(buildTable(exFn, exSn));
                        send(mailTo, exFn + " " + exSn, buildTable(exFn, exSn));
                    }
                }
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public String buildTable(String fn, String sn) throws ClassNotFoundException {
        String out = "<style type=\"text/css\">" +
                "<!--" +
                "body {" +
                "background-color: #003333;" +
                "font-family: Arial,Helvetica,sans-serif;" +
                "font-size: 12px;" +
                "font-style: normal;" +
                "font-weight: lighter;" +
                "font-variant: inherit;" +
                "color: #ffffff;" +
                "}" +
                "p { font-face: arial; color: black; font-size: 12px }" +
                "pre { font-face: arial; color: red; font-size: 14px }" +
                "code { font-face: courier; color: blue; font-size: 12px }" +
                "table.mail {margin-top: auto;" +
                "margin-bottom: auto;" +
                "margin-left: auto;" +
                "margin-right: auto;" +
                "border-top-style: groove;" +
                "border-bottom-style: groove;" +
                "border-left-style: groove;" +
                "border-right-style: groove;" +
                "background-color: #333333;}" +
                "table.mail th{margin-top: auto;" +
                "margin-bottom: auto;" +
                "margin-left: auto;" +
                "margin-right: auto;" +
                "text-align: left;" +
                "vertical-align: middle;" +
                "position: relative;" +
                "width: 20%;" +
                "border-top-style: groove;" +
                "border-bottom-style: groove;" +
                "border-left-style: groove;" +
                "border-right-style: groove;" +
                "color: #ffffff;" +
                "font-size: 13px;" +
                "font-family: Arial,Helvetica,sans-serif;" +
                "background-color: gray;}" +
                "table.mail td{border-top-style: double;" +
                "border-bottom-style: double;" +
                "border-left-style: double;" +
                "border-right-style: double;" +
                "font-family: Arial,Helvetica,sans-serif;" +
                "font-size: 10px;" +
                "color: #000000;" +
                "border-top-color: #ffffff;" +
                "border-bottom-color: #ffffff;" +
                "border-left-color: #ffffff;" +
                "border-right-color: #ffffff;" +
                "text-align: left;" +
                "vertical-align: middle;" +
                "margin-top: auto;" +
                "margin-bottom: auto;" +
                "margin-left: auto;" +
                "margin-right: auto;" +
                "background-color: white;}" +
                "-->" +
                "</style>";
        out += "<html>";
        out += "Liebe/Lieber " + fn + "&nbsp;" + sn + ",<br><br>";
        out += "Du hast Ausstände in der Bierkasse:&nbsp;<br><br>";
        out += "<table class=\"mail\"><tbody><thead>";

        ArrayList<String> sorts;
        Double kumSum = 0.0;
        try {
            sorts = new PricesTableConnector().getSorts();

            out += "<tbody>";


            for (String srt : sorts) {
                Integer cnsm = Integer.parseInt(new ConsumersConnector().getConsumptionForUserAndSort(fn, sn, srt));
                Double price = new PricesTableConnector().getPriceFor(srt);
                Double sum = Math.round(cnsm * price * 100.0) / 100.0;
                kumSum += sum;
                kumSum = Math.round(kumSum * 100.0) / 100.0;
            }
        } catch (SQLException ex) {
            Logger.getLogger(SmtpSimple.class.getName()).log(Level.SEVERE, null, ex);
        }

        out += "<tr><thead><th>&nbsp;</th><th>Rechnungsbetrag:&nbsp;</th><td>" + kumSum + "</td></thead></tr>";
        out += "</tbody></table>";
        out += "<br><br>";
        out += "Bitte überweise den offenen Rechnungsbetrag an:&nbsp;<br><br>";
        out += "<table class=\"mail\"><tbody>";
        out += "<tr><td>Inhaber:&nbsp;</td><td>INHABER HIER</td></tr>";
        out += "<tr><td>Konto:&nbsp;</td><td>KONTONUMMER HIER</td></tr>";
        out += "<tr><td>BLZ:&nbsp;</td><td>BLZ HIER</td></tr>";
        out += "<tr><td>Institut:&nbsp;</td><td>INSTITUT HIER</td></tr>";
        out += "</tbody></table>";
        out += "</html>";
        return out;
    }

    public void send(InternetAddress rcp, String mail, String msg) throws Exception {
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");

        Authenticator auth = new SMTPAuthenticator();
        Session mailSession = Session.getDefaultInstance(props, auth);
        // uncomment for debugging infos to stdout
        // mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject(SUBJECT);
        message.setContent(msg, "text/html");

        message.setFrom(new InternetAddress(FROM_MAIL, FROM_NAME));
        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress("mario@stalinski.name"));

        transport.connect();
        transport.sendMessage(message,
                message.getRecipients(Message.RecipientType.TO));
        transport.close();
    }

    public void run() {
        while (true) {
            try {
                if (System.currentTimeMillis() >= sendAt) {
                    try {
                        initSend();
                        timeStamp = System.currentTimeMillis();
                        sendAt = timeStamp + INTERVAL;
                    } catch (Exception ex) {
                        Logger.getLogger(SmtpSimple.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                t.sleep(1000);


            } catch (InterruptedException ex) {
                Logger.getLogger(SmtpSimple.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = SMTP_AUTH_USER;
            String password = SMTP_AUTH_PWD;
            return new PasswordAuthentication(username, password);
        }
    }
}